function Timer() {
	this._id = 0;
    var self = this;
    this._queue = [];
	
	// TODO 无监听函数时，去掉这个监听
	(function countDownStart(){
		// console.log("无阻塞是 60帧")
		for (var i = 0, item; i < self._queue.length; i++) {
			item = self._queue[i];
			var start = item.start;
			var timestamps = item.timestamps;
			var count = item.count;
			var callback = item.callback;

	        var _now = Date.now();

	        // 距离一开始的时间
			var _left = _now - start;

		    if ((_left) >= (count + 1) * timestamps) {
		    	// 防止是延迟了多次区间，切换浏览器的tab时，requestAnimationFrame 不会被执行
		    	item.count = parseInt((_left / timestamps),10);

				var offset = _now - (start + item.count * timestamps);
				console.log("offset", offset);

				callback && callback();
				if (item.times !== undefined) {
					item.times = item.times > 0? --(item.times): 0;
				}
				if (item.times === 0) {
					self.remove(item._id);
				}
			}
		}

		window.requestAnimationFrame(countDownStart);                  
	})();
}

Timer.prototype = {
    constructor: Timer,
    add: function(callback, timestamps, times) {
    	var _id = this._id++,
    		timeoutId = null;
		
		if (times === 1) {
			// dev
			var start = new Date().getTime();
			// 无阻塞时，原生更快 
	    	timeoutId = setTimeout(() => { 
				// this.remove(_id);
	     		console.log("dev setTimeout", new Date().getTime() - (start + timestamps)); 
			},timestamps); 
		}

		this._queue.push({
			_id: _id,
			start: Date.now(),
			timestamps: timestamps,
			callback: callback,
			count: 0,
			times: times,
			timeoutId: timeoutId
		});

		return _id; //this._queue.length - 1;
    },
    remove: function(id) {
    	this._queue.map((item, i) => {
    		if (item._id === id) {
    			var timeoutId = this._queue[i].timeoutId;
      			// timeoutId && clearTimeout(timeoutId);
      			
      			this._queue.splice(i, 1);
    		}
    	})
    },
    Interval: function(callback, timestamps){
    	return this.add(callback, timestamps)
    },
    Timeout: function(callback, timestamps){
    	return this.add(callback, timestamps, 1);
    },
    ClearTime: function(id){
    	this.remove(id);
    }
};

// here we go
var T = new Timer();
var Interval = T.Interval.bind(T);
var Timeout = T.Timeout.bind(T);
var ClearTime = T.ClearTime.bind(T);


